<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>消息-聊天</title>

    <link rel="stylesheet" href="../../plugins/fontawesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
    <link rel="stylesheet" href="../../plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css">
    <link rel="stylesheet" href="../../adminLTE/css/adminlte.min.css">
    <link rel="stylesheet" href="../css/cloud.css">

    <style>
        img.online  {
            filter: grayscale(0);
        }
        img.offline {
            filter: grayscale(1);
        }
    </style>
</head>
<body class="content-wrapper" style="padding: 15px">
<div class="container-fluid">
    <div class="row">
        <div class="col-md-3">
            <div class="card card-info card-outline" style="margin-bottom: 0;">
                <div id="user" class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-2 mt-2 who" data-id="{{id}}" data-online="{{online}}"
                         style="padding: 10px; border-radius: 3px;cursor: pointer;">
                        <p class="mb-0">
                            <img class="img-circle img-size-32 mr-2 {{class1}}" src="{{image}}">{{name}}
                        </p>
                        <p class="d-flex flex-column text-right mb-0">
                            <span class="badge {{class2}}">{{count}}</span>
                        </p>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-9">
            <div class="card card-info card-outline direct-chat direct-chat-info" style="margin-bottom: 0;">
                <div class="card-body">
                    <div id="message" class="direct-chat-messages" style="padding: 20px">
                        <div id="message-receive" class="direct-chat-msg" style="margin-bottom: 30px;" data-id="{{id}}">
                            <div class="direct-chat-infos clearfix">
                                <span class="direct-chat-name float-left">{{name}}</span>
                                <span class="direct-chat-timestamp float-right">{{time}}</span>
                            </div>
                            <img class="direct-chat-img" src="{{image}}" alt="Message User Image">
                            <div class="direct-chat-text">{{content}}</div>
                        </div>
                        <div id="message-send" class="direct-chat-msg right" style="margin-bottom: 30px;" data-id="{{id}}">
                            <div class="direct-chat-infos clearfix">
                                <span class="direct-chat-name float-right">{{name}}</span>
                                <span class="direct-chat-timestamp float-left">{{time}}</span>
                            </div>
                            <img class="direct-chat-img" src="{{image}}" alt="Message User Image">
                            <div class="direct-chat-text">{{content}}</div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <div class="input-group">
                        <input id="input" placeholder="请输入..." class="form-control">
                        <span class="input-group-append">
                            <button id="send" class="btn btn-info">发送</button>
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../js/common.js"></script>
<script src="../js/child.js"></script>
<script>
    $(".direct-chat-messages").css("height", (window.screen.height - 390) + 'px');

    function UserCtrl() {
        // 用户信息的html模板
        this.template = "";
        // 正在与之聊天的用户
        this.user = undefined;
        // 获取用户信息的html模板
        this.getTemplate = function () {
            this.template = $("#user").prop("innerHTML");
            $("#user").html("");
        };
        // 将用户信息绘制到页面
        this.setUsers = function (users, session) {
            if (Utils.isEmpty(users) || session === undefined) {
                return;
            }
            var htmlOnline = "";
            var htmlOffline = "";
            for (var i = 0; i < users.length; i++) {
                var user = users[i];
                if (user.id === session.id) {
                    continue;
                }
                var image = Utils.getHeadImageForChild(user.image);
                var class1 = Utils.isTrue(user.online) ? "online" : "offline";
                var class2 = Utils.isTrue(user.online) ? "badge-info" : "badge-secondary";
                var count = parent.window.frameCtrl.chatCtrl.countUnread(user.id, session.id);
                var html = this.template
                    .replace(new RegExp("{{id}}", "gm"), user.id)
                    .replace(new RegExp("{{name}}", "gm"), user.userName)
                    .replace(new RegExp("{{online}}", "gm"), user.online)
                    .replace(new RegExp("{{image}}", "gm"), image)
                    .replace(new RegExp("{{count}}", "gm"), count)
                    .replace(new RegExp("{{class1}}", "gm"), class1)
                    .replace(new RegExp("{{class2}}", "gm"), class2);
                if (Utils.isTrue(user.online)) {
                    htmlOnline = htmlOnline + html;
                } else {
                    htmlOffline = htmlOffline + html;
                }
            }
            $("#user").html("").append(htmlOnline).append(htmlOffline);
            if (this.user) {
                $("#user > div[data-id=" + this.user.id + "]").addClass("bg-info");
                $("#user > div[data-id=" + this.user.id + "] span.badge")
                    .removeClass("badge-info").removeClass("badge-secondary")
                    .addClass("badge-danger").html("0");
            }
        };
        // 切换与之聊天的用户
        this.switchUser = function (user) {
            if (this.user) {
                var clazz = this.user.online ? "badge-info" : "badge-secondary";
                $("#user > div[data-id=" + this.user.id + "]").removeClass("bg-info");
                $("#user > div[data-id=" + this.user.id + "] span.badge").removeClass("badge-danger").addClass(clazz);
            }
            $("#user > div[data-id=" + user.id + "]").addClass("bg-info");
            $("#user > div[data-id=" + user.id + "] span.badge")
                .removeClass("badge-info").removeClass("badge-secondary")
                .addClass("badge-danger").html("0");
            this.user = user;
        };
     }

    function MessageCtrl(sessionUser, currUser) {
        // 接收的消息的html模板
        this.templateReceive = "";
        // 发送的消息的html模板
        this.templateSend = "";
        // 获取消息的html模板
        this.getTemplate = function () {
            this.templateReceive = $("#message-receive").prop("outerHTML");
            this.templateSend = $("#message-send").prop("outerHTML");
            $("#message").html("");
        };
        // 将聊天框滑动到最底部
        this.gotoBottom = function () {
            $("#message").scrollTop($("#message")[0].scrollHeight);
        };
        // 添加一条消息到聊天框
        this.addMessage = function (user, message, time, type) {
            var template = "";
            if ("receive" === type) {
                template = this.templateReceive;
            } else if ("send" === type) {
                template = this.templateSend;
            }
            var html = template
                .replace(new RegExp("{{id}}", "gm"), user.id)
                .replace(new RegExp("{{name}}", "gm"), user.userName)
                .replace(new RegExp("{{image}}", "gm"), Utils.getHeadImageForChild(user.image))
                .replace(new RegExp("{{content}}", "gm"), message)
                .replace(new RegExp("{{time}}", "gm"), time);
            $("#message").append(html);
            this.gotoBottom();
        };
        // 切换与之聊天的用户
        this.switchUser = function (currUser, sessionUser, chats) {
            $("#message").html("");
            for (var i = 0; i < chats.length; i++) {
                var chat = chats[i];
                if (chat.from === currUser.id && chat.to === sessionUser.id) {
                    this.addMessage(currUser, chat.message, chat.time, "receive");
                } else if (chat.from === sessionUser.id && chat.to === currUser.id) {
                    this.addMessage(sessionUser, chat.message, chat.time, "send");
                }
            }
        }
    }

    var userCtrl = new UserCtrl();
    // 获取用户信息的html模板
    userCtrl.getTemplate();
    // 尝试将用户信息绘制到页面
    // 如果parent.window.frameCtrl.userCtrl.users为空或parent.window.frameCtrl.authCtrl.session为空则啥也不干，等待事件通知
    userCtrl.setUsers(parent.window.frameCtrl.userCtrl.users, parent.window.frameCtrl.authCtrl.session);

    var messageCtrl = new MessageCtrl();
    // 获取消息的html模板
    messageCtrl.getTemplate();

    // 如果frame中获取了用户，则重新绘制用户信息
    var listener1 = function (users) {
        userCtrl.setUsers(users, parent.window.frameCtrl.authCtrl.session)
    };
    listener1.owner = window.location.href;
    parent.window.frameCtrl.userCtrl.userListener.push(listener1);
    // 如果frame中获取了session，则重新绘制用户信息
    var listener2 = function (session) {
        userCtrl.setUsers(parent.window.frameCtrl.userCtrl.users, session)
    };
    listener2.owner = window.location.href;
    parent.window.frameCtrl.authCtrl.sessionListener.push(listener2);
    // 如果收到了用户上下线的websocket事件，则重新绘制用户信息
    var listener3 = function (event) {
        if (event.type === "ONLINE" || event.type === "OFFLINE") {
            userCtrl.setUsers(parent.window.frameCtrl.userCtrl.users, parent.window.frameCtrl.authCtrl.session);
        }
    };
    listener3.owner = window.location.href;
    parent.window.frameCtrl.websockerCtrl.eventListener.push(listener3);
    // 如果收到了即时通讯的websocket消息
    // 1. 如果发来用户就是当前正在聊天用户，则将消息内容绘制到消息框
    // 2. 如果发来用户是其他用户，则将该用户的未读消息数量+1
    var listener4 = function (chat) {
        if (userCtrl.user && userCtrl.user.id === chat.userId) {
            var time = new Date().format("yyyy-MM-dd HH:mm:ss");
            messageCtrl.addMessage(userCtrl.user, chat.message, time, "receive");

            parent.window.frameCtrl.chatCtrl.readChats(chat.userId, parent.window.frameCtrl.authCtrl.session.id);
            parent.window.frameCtrl.chatCtrl.setChats(parent.window.frameCtrl.authCtrl.session.id, parent.window.frameCtrl.userCtrl.users);
        } else {
            var $count = $("#user > div[data-id=" + chat.userId + "] span.badge");
            if ($count.length === 1) {
                $count.html(parseInt($count.html()) + 1);
            }
        }
    };
    listener4.owner = window.location.href;
    parent.window.frameCtrl.websockerCtrl.chatListener.push(listener4);

    $("#send").click(function () {
        if (userCtrl.user === undefined) {
            return;
        }
        var message = $("#input").val();
        if (Utils.isEmpty(message)) {
            return;
        }
        var webSocketChat = {};
        webSocketChat.userId = userCtrl.user.id;
        webSocketChat.message = message;
        var webSocketMessage = {};
        webSocketMessage.type = "CHAT";
        webSocketMessage.message = webSocketChat;
        parent.window.frameCtrl.websockerCtrl.send(JSON.stringify(webSocketMessage));
        parent.window.frameCtrl.chatCtrl.addChat(parent.window.frameCtrl.authCtrl.session.id, userCtrl.user.id, message, true);
        messageCtrl.addMessage(parent.window.frameCtrl.authCtrl.session, message, new Date().format("yyyy-MM-dd HH:mm:ss"), "send");
        $("#input").val("");
    });
    $("#user").on("click", ".who", function () {
        var userId = $(this).attr("data-id");
        var user = parent.window.frameCtrl.userCtrl.getUser(userId);
        userCtrl.switchUser(user);

        var chats = parent.window.frameCtrl.chatCtrl.searchChats(user.id, parent.window.frameCtrl.authCtrl.session.id);
        messageCtrl.switchUser(user, parent.window.frameCtrl.authCtrl.session, chats);
        parent.window.frameCtrl.chatCtrl.readChats(user.id, parent.window.frameCtrl.authCtrl.session.id);
        parent.window.frameCtrl.chatCtrl.setChats(parent.window.frameCtrl.authCtrl.session.id, parent.window.frameCtrl.userCtrl.users);
    });
</script>

</body>
</html>